package com.weifly.weistock.web.controller.record;

import com.weifly.weistock.core.chart.ChartConverter;
import com.weifly.weistock.core.chart.bo.ChartConfigBO;
import com.weifly.weistock.core.chart.bo.ChartDataSetBO;
import com.weifly.weistock.core.common.Result;
import com.weifly.weistock.core.constant.WeistockConstants;
import com.weifly.weistock.core.market.bo.StockDayBO;
import com.weifly.weistock.core.market.bo.StockKLineBO;
import com.weifly.weistock.core.util.DateUtils;
import com.weifly.weistock.core.util.WeistockUtils;
import com.weifly.weistock.module.stockdata.StockDataHoldService;
import com.weifly.weistock.record.asset.AssetMonitorService;
import com.weifly.weistock.record.asset.AssetUtils;
import com.weifly.weistock.record.asset.domain.AssetDayDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户资产
 *
 * @author weifly
 * @since 2019/9/19
 */
@Controller
@RequestMapping(value = "/record/asset")
public class AssetMonitorController {

    private Logger log = LoggerFactory.getLogger(AssetMonitorController.class);

    @Autowired
    private AssetMonitorService assetMonitorService;

    @Autowired
    private StockDataHoldService stockDataHoldService;

    /**
     * 记录首页
     */
    @RequestMapping(value = "/index")
    public String index(HttpServletRequest request, HttpServletResponse response) {
        return "record/asset/index";
    }

    /**
     * 资产走势图
     */
    @RequestMapping(value = "/chart")
    public String chart(){
        return "record/asset/chart";
    }

    /**
     * 加载chart数据
     */
    @ResponseBody
    @RequestMapping("/loadChartData")
    public Result loadChartData(HttpServletRequest request) {
        ChartConfigBO chartConfig = ChartConverter.getChartConfig(request);
        ChartDataSetBO dataSet = new ChartDataSetBO();
        // 加载资金列表
        List<AssetDayDto> assetDayList = this.assetMonitorService.loadChartDayList(chartConfig.getDay());
        AssetUtils.fillAssetDataSet(dataSet, assetDayList);
        // 加载对比数据
        for (String stockCode : chartConfig.getOverList()) {
            StockKLineBO stockKLineBO = this.stockDataHoldService.getStockData(stockCode);
            if (stockKLineBO != null) {
                List<StockDayBO> stockDayList = AssetUtils.loadStockDayList(stockKLineBO, chartConfig.getDay());
                AssetUtils.fillStockDataSet(dataSet, stockDayList, stockCode, stockKLineBO.getStockName());
            }
        }
        return Result.createSuccessResult(dataSet);
    }

    /**
     * 添加编辑资产记录
     * @return
     */
    @RequestMapping(value = "/editDay")
    public String editDay(){
        return "record/asset/editDay";
    }

    /**
     * 更新资产记录
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateAssetDay")
    public Result updateAssetDay(HttpServletRequest request){
        String dayField = request.getParameter("dayField");
        String error = DateUtils.checkDateString(dayField);
        if (error != null) {
            return Result.createErrorResult("日期错误：" + error);
        }
        String assetField = request.getParameter("assetField");
        if(StringUtils.isBlank(assetField)){
            return Result.createErrorResult("缺少字段：总资产");
        }
        double asset = Double.parseDouble(assetField);
        if(asset<=0){
            return Result.createErrorResult("总资产应大于0");
        }

        AssetDayDto assetDay = new AssetDayDto();
        assetDay.setDay(dayField);
        assetDay.setAsset(asset);
        this.assetMonitorService.updateAsset(assetDay);

        return Result.createSuccessResult(null);
    }

    /**
     * 资产记录列表
     */
    @RequestMapping(value = "/list")
    public String list(){
        return "record/asset/list";
    }

    /**
     * 加载资产记录列表
     */
    @ResponseBody
    @RequestMapping("/getDayList")
    public Result getDayList(HttpServletRequest request){
        try{
            String day = request.getParameter("day"); // 加载此天前的10条记录
            if(StringUtils.isBlank(day)){
                day = null;
            }
            int limit = WeistockConstants.PAGE_LIMIT;

            // 降序排列的，多取一条数据，以便计算rate
            List<AssetDayDto> dayList = this.assetMonitorService.getAssetDayList(day, limit+1);

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("haveMore", dayList.size()>limit);

            List<Map<String, Object>> dayInfoList = new ArrayList<>();
            if(dayList.size()>0){
                DecimalFormat decimalFormat = new DecimalFormat("0.##");
                for(int i=0;i<dayList.size();i++){
                    AssetDayDto dayDto = dayList.get(i);
                    Map<String, Object> dayInfo = new HashMap<>();
                    dayInfo.put("day", dayDto.getDay());
                    dayInfo.put("asset", dayDto.getAsset());
                    if(i>0){
                        AssetDayDto bigDayDto = dayList.get(i-1);
                        Map<String, Object> bigDayInfo = dayInfoList.get(i-1);
                        bigDayInfo.put("diff", WeistockUtils.subtract(bigDayDto.getAsset(), dayDto.getAsset()));
                        bigDayInfo.put("rate", this.calcRate(dayDto, bigDayDto, decimalFormat));
                    }
                    dayInfoList.add(dayInfo);
                }
                // 只返回limit条记录
                if(dayInfoList.size()>limit){
                    dayInfoList = dayInfoList.subList(0, limit);
                }
            }
            dataMap.put("dayList", dayInfoList);

            return Result.createSuccessResult(dataMap);
        }catch(Exception e){
            log.error("加载资产记录列表出错", e);
            return Result.createErrorResult("加载资产记录列表出错");
        }
    }

    private double calcRate(AssetDayDto dayDto, AssetDayDto bigDayDto, DecimalFormat decimalFormat){
        double rate = 0;
        if(dayDto.getAsset()>0){
            double diff = WeistockUtils.subtract(bigDayDto.getAsset(), dayDto.getAsset());
            rate = WeistockUtils.divide(WeistockUtils.multi(diff, 100), dayDto.getAsset());
            rate = Double.parseDouble(decimalFormat.format(rate));
        }
        return rate;
    }
}
